package com.example.excel.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.example.exception.BadRequestException;
import com.example.pojo.CourseTableEntity;
import com.example.service.CourseTableService;
import com.example.utils.SecurityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author
 * @description: 考试excel导入
 * @date 2022/3/17 8:20 PM
 */
public class CourseTableDataListener implements ReadListener<CourseTableEntity> {
	private static final int BATCH_COUNT = 50;
	private List<CourseTableEntity> courseTableEntities = ListUtils.newArrayListWithCapacity(BATCH_COUNT);
	private final CourseTableService courseTableService;

	public CourseTableDataListener(CourseTableService courseTableService) {
		this.courseTableService = courseTableService;
	}

	@Override
	public void invoke(CourseTableEntity o, AnalysisContext analysisContext) {
		UserDetails currentUser = SecurityUtils.getCurrentUser();
		JSONObject jsonObject = new JSONObject(new JSONObject(currentUser).get("user"));
		List<String> list = jsonObject.getJSONArray("jobs")
				.toList(JSONObject.class).stream()
				.map(i -> i.getStr("name")).collect(Collectors.toList());
		List<String> strings = Optional.of(list).orElse(ListUtils.newArrayList());
		if (!strings.contains(o.getCourse())) {
			throw new BadRequestException("当前老师和excel课程名称不匹配");
		}
		Long currentUserId = SecurityUtils.getCurrentUserId();
		o.setUserId(currentUserId);
		courseTableEntities.add(o);
		if (courseTableEntities.size() >= BATCH_COUNT) {
			saveData();
			// 存储完成清理 list
			courseTableEntities = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
		}
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {
		// 保存
		saveData();
	}

	/**
	 * 保存到数据库
	 */
	public void saveData() {
		if (!courseTableEntities.isEmpty()) {
			List<CourseTableEntity> courseTableEntityList = courseTableService.selectByStuNumber(this.courseTableEntities.stream()
							.map(CourseTableEntity::getStuNumber).collect(Collectors.toList()),
					SecurityUtils.getCurrentUserId());
			if (CollectionUtil.isNotEmpty(courseTableEntityList)) {
				courseTableService.deleteBatch(courseTableEntityList.stream().map(CourseTableEntity::getId).collect(Collectors.toList()));
			}
			courseTableService.batchInsert(courseTableEntities);
		}
	}
}

